import Vue from "vue";
import AppConf from "@/config";

export function getUuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
  return s.join("");
}

export function getSocket(params, methods = {}) {
  return new Promise((resolve, reject) => {
    // uuid
    const uuid = getUuid();
    // 心跳间隔(s)
    const heartbeatSpace = 120;
    // 重连的次数
    let reconnectCount = 0;
    // 是否正在连接
    let reconnectIng = false;
    // 重连的时间间隔
    let reconnectSpace = 2000;
    // socket配置 默认不重连
    let { connection = "", appendUuid = true, reconnectMax = 0 } = params;
    // socket信息回调
    const { success, error } = methods;
    // 没有地址抛出错误
    if (!connection) {
      reject("没有定义链接地址");
      return;
    }
    // 默认添加uuid
    if (appendUuid) {
      if (connection.includes("?")) {
        connection = [connection, `connectionId=${uuid}`].join("&");
      } else {
        connection = [connection, `connectionId=${uuid}`].join("?");
      }
    }
    function initSocket() {
      // 创建socket实例
      const socket = new WebSocket(connection);
      // 监听socket打开
      socket.onopen = function() {
        resolve(socket);
        console.log("浏览器WebSocket已打开");
        if (AppConf.$config.socketNotHeart) {
          // 不进行心跳连接
          return;
        }
        socket.heartbeat();
      };
      // 监听socket消息接收
      socket.onmessage = function(msg) {
        // 转换为json对象
        const data = JSON.parse(msg.data);
        const { type, message } = data;
        const { methods = {} } = socket;
        // bus 通讯分发事件
        Vue.prototype.$EventBus.$emit(type, message);
        // 分发回调
        if (methods[type]) {
          methods[type](message);
        }
      };
      // 监听socket错误
      socket.onerror = function() {
        // reconnect();
        socket.methods.ONERROR();
        console.log("WebSocket连接出错,将尝试重连");
      };
      // 监听socket关闭
      socket.onclose = function() {
        socket.methods.ONCLOSE();
        // reconnect();
        console.log("WebSocket已关闭,将尝试重连");
      };
      // 添加心跳
      function socketHeartBeat() {
        socket.heartbeat = function() {
          // console.log(socket);
          if (socket.readyState === 1) {
            const para = {
              type: "HEARTBEAT_REQUEST",
              message: {
                connectionId: uuid
              }
            };
            socket.send(JSON.stringify(para));
            setTimeout(() => {
              socket.heartbeat();
            }, heartbeatSpace * 1000);
          }
        };
      }

      socketHeartBeat();
    }
    // 不能使用（socket可以主动关闭）
    function reconnect() {
      if (reconnectMax > 0) {
        // 防止重复调用
        if (reconnectIng) {
          return;
        }
        reconnectIng = true;
        reconnectCount++;
        if (reconnectCount <= reconnectMax) {
          setTimeout(() => {
            reconnectIng = false;
            initSocket();
          }, reconnectSpace);
        } else {
          reject("websocket重连失败");
        }
      } else {
        reject("websocket连接失败");
      }
    }

    initSocket();
  });
}
